import React, { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import styles from './index.module.css'
import img from './img/image.png'
import { FilterOutlined } from '@ant-design/icons';
import Nabar from '../../conpoment/Nabar'
// 发票数据接口
interface InvoiceData {
  id: string
  type: string
  status: 'issued' | 'reversed'
  statusText: string
  patientName: string
  invoiceNo: string
  businessType: string
  issueTime: string
  hasPreview?: boolean
  canSendEmail?: boolean
}
// 患者数据接口
interface PatientData {
  id: string
  name: string
  idNumber: string
}
const Invoice: React.FC = () => {
  const navigate = useNavigate()
  const [showSwitchModal, setShowSwitchModal] = useState(false)
  const [showEmailModal, setShowEmailModal] = useState(false)
  const [emailAddress, setEmailAddress] = useState('')
  const [currentInvoiceId, setCurrentInvoiceId] = useState<string>('')
  const [currentPatient, setCurrentPatient] = useState<PatientData>({
    id: '1',
    name: '王小柯',
    idNumber: '2015****10'
  })
  // 患者列表数据
  const patients: PatientData[] = [
    { id: '1', name: '王小柯', idNumber: '2015****10' },
    { id: '2', name: '李玲玲', idNumber: '2016****11' },
    { id: '3', name: '张小红', idNumber: '2017****12' }
  ]
  // 发票列表数据
  const invoices: InvoiceData[] = [
    {
      id: '1',
      type: '门诊发票',
      status: 'issued',
      statusText: '已开具',
      patientName: '王小柯',
      invoiceNo: '0050745821',
      businessType: '门诊挂号',
      issueTime: '2020-01-01 10:20:36',
      hasPreview: true,
      canSendEmail: true
    },
    {
      id: '2',
      type: '门诊发票',
      status: 'reversed',
      statusText: '已冲红',
      patientName: '王小柯',
      invoiceNo: '0050745821',
      businessType: '门诊挂号',
      issueTime: '2020-01-01 10:20:36',
      hasPreview: false,
      canSendEmail: false
    }
  ]
  // 处理返回
  const handleBack = () => {
    navigate(-1)
  }

  // 处理患者切换
  const handleSwitchClick = () => {
    setShowSwitchModal(true)
  }

  // 关闭切换弹窗
  const handleCloseModal = () => {
    setShowSwitchModal(false)
  }

  // 切换患者
  const handleSwitchPatient = (patient: PatientData) => {
    setCurrentPatient(patient)
    setShowSwitchModal(false)
  }

  // 处理筛选
  const handleFilter = () => {
    // 筛选功能实现
    console.log('筛选发票')
  }

  // 处理预览
  const handlePreview = (invoiceId: string) => {
    console.log('预览发票:', invoiceId)
    // 这里可以添加预览发票的逻辑
  }

  // 处理发送邮箱
  const handleSendEmail = (invoiceId: string) => {
    setCurrentInvoiceId(invoiceId)
    setShowEmailModal(true)
  }

  // 关闭邮箱弹窗
  const handleCloseEmailModal = () => {
    setShowEmailModal(false)
    setEmailAddress('')
    setCurrentInvoiceId('')
  }

  // 处理邮箱输入
  const handleEmailChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEmailAddress(e.target.value)
  }

  // 验证邮箱格式
  const validateEmail = (email: string) => {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
    return emailRegex.test(email)
  }

  // 确认发送邮箱
  const handleConfirmSend = () => {
    if (!emailAddress.trim()) {
      alert('请输入邮箱地址')
      return
    }
    
    if (!validateEmail(emailAddress)) {
      alert('请输入有效的邮箱地址')
      return
    }

    // 这里可以添加实际的发送邮箱逻辑
    console.log('发送发票到邮箱:', emailAddress, '发票ID:', currentInvoiceId)
    
    // 模拟发送成功
    alert('发票已发送到您的邮箱')
    handleCloseEmailModal()
  }

  return (
    <div className={styles.container}>
      {/* 导航栏 */}
      <Nabar title="电子票据" onBack={handleBack} />

      {/* 患者信息栏 */}
      <div className={styles.patientInfo}>
        <div className={styles.patientDetails}>
          <span className={styles.patientName}>{currentPatient.name}</span>
          <span className={styles.patientId}>{currentPatient.idNumber}</span>
        </div>
        <button className={styles.switchButton} onClick={handleSwitchClick}>
          <span className={styles.switchIcon}>👤⇄</span>
          <span className={styles.switchText}>切换</span>
        </button>
      </div>

      {/* 发票列表标题 */}
      <div className={styles.listHeader}>
        <h3 className={styles.listTitle}>发票列表</h3>
        <button className={styles.filterButton} onClick={handleFilter}>
          <span className={styles.filterIcon}><FilterOutlined /></span>
          <span className={styles.filterText}>筛选</span>
        </button>
      </div>

      {/* 发票列表 */}
      <div className={styles.invoiceList}>
        {invoices.map((invoice) => (
          <div key={invoice.id} className={styles.invoiceCard}>
            {/* 状态指示条 */}
            <div className={`${styles.statusBar} ${styles[invoice.status]}`}></div>

            <div className={styles.invoiceContent}>
              {/* 发票类型和状态 */}
              <div className={styles.invoiceHeader}>
                <span className={styles.invoiceType}>{invoice.type}</span>
                <span className={`${styles.invoiceStatus} ${styles[invoice.status]}`}>
                  {invoice.statusText}
                </span>
              </div>

              {/* 发票详情 */}
              <div className={styles.invoiceDetails}>
                <div>
                        <div className={styles.detailRow}>
                  <span className={styles.label}>就诊人:</span>
                  <span className={styles.value}>{invoice.patientName}</span>
                </div>
                <div className={styles.detailRow}>
                  <span className={styles.label}>票据号:</span>
                  <span className={styles.value}>{invoice.invoiceNo}</span>
                </div>
                <div className={styles.detailRow}>
                  <span className={styles.label}>业务类型:</span>
                  <span className={styles.value}>{invoice.businessType}</span>
                </div>
                <div className={styles.detailRow}>
                  <span className={styles.label}>开票时间:</span>
                  <span className={styles.value}>{invoice.issueTime}</span>
                </div>
                </div>
                <div>
                  {/* 预览区域 */}
                  {invoice.hasPreview && (
                    <div className={styles.previewArea}>
                      <div className={styles.previewThumbnail}>
                        <div className={styles.thumbnailImage}><img src={img} alt="" />  </div>
                        <div className={styles.previewHint}>点击预览</div>
                      </div>
                    </div>
                  )}
                </div>
              </div>
              {/* 操作按钮 */}
              {invoice.canSendEmail && (
                <div className={styles.actionArea}>
                  <button
                    className={styles.sendEmailButton}
                    onClick={() => handleSendEmail(invoice.id)}
                  >
                    发送邮箱
                  </button>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* 底部提示 */}
      <div className={styles.footerHint}>
        默认加载近三个月内的发票
      </div>

      {/* 患者切换弹窗 */}
      {showSwitchModal && (
        <div className={styles.modalOverlay} onClick={handleCloseModal}>
          <div className={styles.modalContent} onClick={(e) => e.stopPropagation()}>
            <div className={styles.modalHeader}>
              <h3>选择就诊人</h3>
              <button className={styles.closeButton} onClick={handleCloseModal}>×</button>
            </div>
            <div className={styles.patientList}>
              {patients.map((patient) => (
                <div
                  key={patient.id}
                  className={`${styles.patientItem} ${currentPatient.id === patient.id ? styles.selected : ''}`}
                  onClick={() => handleSwitchPatient(patient)}
                >
                  <div className={styles.patientInfo}>
                    <span className={styles.patientName}>{patient.name}</span>
                    <span className={styles.patientId}>{patient.idNumber}</span>
                  </div>
                  {currentPatient.id === patient.id && (
                    <span className={styles.checkIcon}>✓</span>
                  )}
                </div>
              ))}
            </div>
            <div className={styles.modalFooter}>
              <button className={styles.addPatientButton}>添加就诊人</button>
            </div>
          </div>
        </div>
      )}

      {/* 邮箱发送确认弹窗 */}
      {showEmailModal && (
        <div className={styles.modalOverlay} onClick={handleCloseEmailModal}>
          <div className={styles.emailModalContent} onClick={(e) => e.stopPropagation()}>
            <div className={styles.emailModalHeader}>
              <h3>请确认邮箱发送地址</h3>
            </div>
            <div className={styles.emailModalBody}>
              <input
                type="email"
                className={styles.emailInput}
                placeholder="输入用来接收电子发票邮件"
                value={emailAddress}
                onChange={handleEmailChange}
              />
            </div>
            <div className={styles.emailModalFooter}>
              <button 
                className={styles.cancelButton}
                onClick={handleCloseEmailModal}
              >
                取消
              </button>
              <button 
                className={styles.confirmButton}
                onClick={handleConfirmSend}
              >
                确定发送
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default Invoice